from PyQt5.QtWidgets import (QMessageBox, QButtonGroup, QTableWidgetItem, 
                           QHeaderView, QAbstractItemView, QPushButton, QDialog, QFormLayout,
                           QVBoxLayout, QHBoxLayout, QLineEdit, QLabel)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.uic import loadUi
from src.utils.ui_utils import center_window
from src.models.user_model import UserModel
from src.models.product_model import ProductModel
from src.models.order_model import OrderModel

class ProductEditDialog(QDialog):
    """商品编辑对话框"""
    
    def __init__(self, parent=None, product=None):
        super().__init__(parent)
        self.product = product
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("编辑商品" if self.product else "添加商品")
        self.setFixedSize(400, 200)
        
        layout = QFormLayout()
        
        # 商品名称
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入商品名称")
        layout.addRow("商品名称:", self.name_input)
        
        # 价格
        self.price_input = QLineEdit()
        self.price_input.setPlaceholderText("请输入价格")
        layout.addRow("价格(元):", self.price_input)
        
        # 如果是编辑模式，填入现有数据
        if self.product:
            self.name_input.setText(self.product.product_name)
            self.price_input.setText(str(self.product.price))
        
        # 按钮
        button_layout = QHBoxLayout()
        self.save_button = QPushButton("保存")
        self.cancel_button = QPushButton("取消")
        
        self.save_button.clicked.connect(self.save_product)
        self.cancel_button.clicked.connect(self.reject)
        
        button_layout.addWidget(self.cancel_button)
        button_layout.addWidget(self.save_button)
        
        layout.addRow(button_layout)
        self.setLayout(layout)
        
        center_window(self)
        
    def save_product(self):
        """保存商品"""
        name = self.name_input.text().strip()
        price_text = self.price_input.text().strip()
        
        if not name:
            QMessageBox.warning(self, "警告", "请输入商品名称！")
            return
            
        try:
            price = float(price_text)
            if price <= 0:
                QMessageBox.warning(self, "警告", "价格必须大于0！")
                return
        except ValueError:
            QMessageBox.warning(self, "警告", "请输入有效的价格！")
            return
            
        if self.product:
            # 编辑模式
            if ProductModel.update_product(self.product.id, name, price):
                QMessageBox.information(self, "成功", "商品更新成功！")
                self.accept()
            else:
                QMessageBox.warning(self, "失败", "商品更新失败！")
        else:
            # 添加模式
            if ProductModel.add_product(name, price):
                QMessageBox.information(self, "成功", "商品添加成功！")
                self.accept()
            else:
                QMessageBox.warning(self, "失败", "商品添加失败！可能商品名已存在。")

class AdminMainView:
    """管理员主界面视图类"""
    
    def __init__(self, controller):
        # 保存控制器引用
        self.controller = controller
        
        # 加载UI文件
        self.ui = loadUi('src/ui/admin.ui')
        
        # 创建按钮组，确保只能选中一个导航按钮
        self.nav_button_group = QButtonGroup()
        self.nav_button_group.addButton(self.ui.shopManageButton)
        self.nav_button_group.addButton(self.ui.orderButton)
        self.nav_button_group.addButton(self.ui.adminInfoButton)
        
        # 连接导航按钮事件
        self.ui.shopManageButton.clicked.connect(self.on_shop_manage_clicked)
        self.ui.orderButton.clicked.connect(self.on_order_manage_clicked)
        self.ui.adminInfoButton.clicked.connect(self.on_admin_info_clicked)
        self.ui.logoutButton.clicked.connect(self.on_logout_clicked)
        
        # 连接功能按钮事件 - 删除不存在的刷新按钮连接
        self.ui.addProductButton.clicked.connect(self.add_product)
        self.ui.editProductButton.clicked.connect(self.edit_product)
        self.ui.deleteProductButton.clicked.connect(self.delete_product)
        self.ui.startDeliveryButton.clicked.connect(self.start_delivery)
        
        # 设置表格列宽
        self.setup_tables()
        
        # 设置窗口居中显示
        center_window(self.ui)
        
    def setup_tables(self):
        """设置表格列宽"""
        # 商品表格列宽设置
        product_header = self.ui.productTable.horizontalHeader()
        product_header.setSectionResizeMode(QHeaderView.Stretch)
        
        # 订单表格列宽设置
        order_header = self.ui.orderTable.horizontalHeader()
        order_header.setSectionResizeMode(QHeaderView.Stretch)
        
    def set_welcome_message(self, username):
        """设置欢迎信息"""
        self.ui.welcomeLabel.setText(f"管理员控制台 - 欢迎，{username}！")
        
    def show(self):
        """显示管理员主界面"""
        self.ui.show()
        # 默认显示商品管理页面并加载商品
        self.ui.stackedWidget.setCurrentWidget(self.ui.productManagePage)
        self.load_products()
        
    def hide(self):
        """隐藏管理员主界面"""
        self.ui.hide()
        
    def on_shop_manage_clicked(self):
        """店铺管理按钮点击事件"""
        self.ui.stackedWidget.setCurrentWidget(self.ui.productManagePage)
        self.load_products()
        
    def on_order_manage_clicked(self):
        """订单管理按钮点击事件"""
        self.ui.stackedWidget.setCurrentWidget(self.ui.orderManagePage)
        self.load_orders()
        
    def on_admin_info_clicked(self):
        """管理员信息按钮点击事件"""
        self.ui.stackedWidget.setCurrentWidget(self.ui.adminInfoPage)
        self.update_admin_info_display()
        
    def update_admin_info_display(self):
        """更新管理员信息显示"""
        try:
            current_user = self.controller.current_user
            if current_user:
                admin_info_text = f"""基本信息

管理员ID：{current_user.id}
用户名：{current_user.username}
手机号：{current_user.phone}
性别：{current_user.gender}
年龄：{current_user.get_age_display()}
角色：{current_user.get_role_name()}

管理员权限
商品管理 | 订单管理 | 系统配置

管理员信息仅供查看"""
                
                self.ui.adminInfoLabel.setText(admin_info_text)
            else:
                QMessageBox.warning(self.ui, "错误", "无法获取管理员信息！")
        except Exception as e:
            QMessageBox.critical(self.ui, "错误", f"获取管理员信息失败：{str(e)}")
        
    def load_products(self):
        """加载商品数据"""
        try:
            products = ProductModel.get_all_products()
            self.ui.productTable.setRowCount(len(products))
            
            for row, product in enumerate(products):
                self.ui.productTable.setItem(row, 0, QTableWidgetItem(str(product.id)))
                self.ui.productTable.setItem(row, 1, QTableWidgetItem(product.product_name))
                self.ui.productTable.setItem(row, 2, QTableWidgetItem(f"{product.price:.2f}"))
                self.ui.productTable.setItem(row, 3, QTableWidgetItem(str(product.sales)))
                
        except Exception as e:
            QMessageBox.warning(self.ui, "错误", f"加载商品失败：{str(e)}")
            
    def add_product(self):
        """添加商品"""
        dialog = ProductEditDialog(self.ui)
        if dialog.exec_() == QDialog.Accepted:
            # 删除刷新代码，不自动刷新
            pass
            
    def edit_product(self):
        """编辑商品"""
        current_row = self.ui.productTable.currentRow()
        if current_row < 0:
            QMessageBox.warning(self.ui, "警告", "请选择要编辑的商品！")
            return
            
        product_id = int(self.ui.productTable.item(current_row, 0).text())
        products = ProductModel.get_all_products()
        product = next((p for p in products if p.id == product_id), None)
        
        if product:
            dialog = ProductEditDialog(self.ui, product)
            if dialog.exec_() == QDialog.Accepted:
                # 删除刷新代码，不自动刷新
                pass
                
    def delete_product(self):
        """删除商品"""
        current_row = self.ui.productTable.currentRow()
        if current_row < 0:
            QMessageBox.warning(self.ui, "警告", "请选择要删除的商品！")
            return
            
        product_id = int(self.ui.productTable.item(current_row, 0).text())
        product_name = self.ui.productTable.item(current_row, 1).text()
        
        reply = QMessageBox.question(
            self.ui, 
            '确认删除', 
            f'确定要删除商品 "{product_name}" 吗？\n此操作不可撤销！',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            if ProductModel.delete_product(product_id):
                QMessageBox.information(self.ui, "成功", "商品删除成功！")
                # 删除刷新代码，不自动刷新
            else:
                QMessageBox.warning(self.ui, "失败", "商品删除失败！")
        
    def load_orders(self):
        """加载订单数据"""
        try:
            orders = OrderModel.get_all_orders()
            self.ui.orderTable.setRowCount(len(orders))
            
            for row, order in enumerate(orders):
                self.ui.orderTable.setItem(row, 0, QTableWidgetItem(str(order.id)))
                self.ui.orderTable.setItem(row, 1, QTableWidgetItem(order.product_name))
                self.ui.orderTable.setItem(row, 2, QTableWidgetItem(f"{order.price:.2f}"))
                self.ui.orderTable.setItem(row, 3, QTableWidgetItem(order.customer_name))
                self.ui.orderTable.setItem(row, 4, QTableWidgetItem(order.customer_phone))
                
                # 状态列，根据状态显示不同颜色
                status_item = QTableWidgetItem(order.get_status_text())
                if order.delivery_status == 0:
                    status_item.setBackground(QColor(255, 165, 0))  # 橙色
                elif order.delivery_status == 1:
                    status_item.setBackground(QColor(135, 206, 235))  # 蓝色
                else:
                    status_item.setBackground(QColor(144, 238, 144))  # 绿色
                self.ui.orderTable.setItem(row, 5, status_item)
                
                # 下单时间
                if order.order_time:
                    time_str = order.order_time.strftime("%Y-%m-%d %H:%M:%S")
                    self.ui.orderTable.setItem(row, 6, QTableWidgetItem(time_str))
                else:
                    self.ui.orderTable.setItem(row, 6, QTableWidgetItem("未知"))
                
        except Exception as e:
            QMessageBox.warning(self.ui, "错误", f"加载订单失败：{str(e)}")
            
    def start_delivery(self):
        """开始派送"""
        current_row = self.ui.orderTable.currentRow()
        if current_row < 0:
            QMessageBox.warning(self.ui, "警告", "请选择要派送的订单！")
            return
            
        order_id = int(self.ui.orderTable.item(current_row, 0).text())
        status_text = self.ui.orderTable.item(current_row, 5).text()
        
        if status_text != "待派发":
            QMessageBox.warning(self.ui, "警告", "只能派送待派发的订单！")
            return
            
        reply = QMessageBox.question(
            self.ui, 
            '确认派送', 
            f'确定要开始派送订单 {order_id} 吗？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            if OrderModel.start_delivery(order_id):
                QMessageBox.information(self.ui, "成功", "订单已开始派送！")
                # 删除刷新代码，不自动刷新
            else:
                QMessageBox.warning(self.ui, "失败", "开始派送失败！")
            
    def on_logout_clicked(self):
        """退出登录按钮点击事件"""
        reply = QMessageBox.question(
            self.ui, 
            '确认退出', 
            '确定要退出管理员控制台吗？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.controller.logout()